import { Context } from 'koa'
import { dynamicCollectionService } from '../services/dynamicCollection'
import { IDynamicCollectionConfig } from '../models/dynamicCollection'

class DynamicCollection {
  /**
   * 创建集合
   */
  async createCollection(ctx: Context) {
    try {
      const config = ctx.request.body as any
      const result = await dynamicCollectionService.createCollection(config)
      ctx.status = 201
      ctx.body = result
    } catch (error: any) {
      ctx.status = error.message.includes('already exists') ? 409 : 500
      ctx.body = {
        success: false,
        error: error.message
      }
    }
  }

  /**
   * 获取所有集合
   */
  async getCollections(ctx: Context) {
    try {
      const collections = await dynamicCollectionService.getAllCollections()
      ctx.status = 200
      ctx.body = {
        success: true,
        data: collections
      }
    } catch (error: any) {
      ctx.status = 500
      ctx.body = {
        success: false,
        error: error.message
      }
    }
  }

  /**
   * 获取集合详情
   */
  async getCollection(ctx: Context) {
    try {
      const { name } = ctx.params
      const collection = await dynamicCollectionService.getCollectionByName(
        name
      )
      ctx.status = 200
      ctx.body = {
        success: true,
        data: collection
      }
    } catch (error: any) {
      ctx.status = error.message.includes('not found') ? 404 : 500
      ctx.body = {
        success: false,
        error: error.message
      }
    }
  }

  /**
   * 删除集合
   */
  async deleteCollection(ctx: Context) {
    try {
      const { name } = ctx.params
      const result = await dynamicCollectionService.deleteCollection(name)
      ctx.status = result.success ? 200 : 404
      ctx.body = result
    } catch (error: any) {
      ctx.status = 500
      ctx.body = {
        success: false,
        error: error.message
      }
    }
  }

  /**
   * 更新集合
   */
  async updateCollection(ctx: Context) {
    try {
      const { name } = ctx.params
      const updateData = ctx.request.body as Partial<IDynamicCollectionConfig>
      const result = await dynamicCollectionService.updateCollection(name, updateData)
      ctx.status = result.success ? 200 : 404
      ctx.body = result
    } catch (error: any) {
      ctx.status = error.message.includes('not found') ? 404 : 500
      ctx.body = {
        success: false,
        error: error.message
      }
    }
  }

  /**
   * 向集合添加文档
   */
  async createDocument(ctx: Context) {
    try {
      const { collectionName } = ctx.params
      const data = ctx.request.body as any
      const document = await dynamicCollectionService.createDocument(
        collectionName,
        data
      )
      ctx.status = 201
      ctx.body = {
        success: true,
        data: document
      }
    } catch (error: any) {
      ctx.status = error.message.includes('not found') ? 404 : 500
      ctx.body = {
        success: false,
        error: error.message
      }
    }
  }

  /**
   * 查询集合中的文档
   */
  async getDocuments(ctx: Context) {
    try {
      const { collectionName } = ctx.params
      const { page, limit, fuzzy, n, ...filter } = ctx.query as any

      // 处理查询参数
      const options = {
        page: parseInt(page) || 1,
        limit: parseInt(limit) || 10
      }

      // 处理过滤条件
      const parsedFilter: any = {}
      Object.keys(filter).forEach((key) => {
        // 排除常见的非过滤参数
        if (key !== 'page' && key !== 'limit' && key !== 'fuzzy' && key !== 'n') {
          try {
            parsedFilter[key] = JSON.parse(filter[key])
          } catch {
            parsedFilter[key] = filter[key]
          }
        }
      })

      const result = await dynamicCollectionService.findDocuments(
        collectionName,
        parsedFilter,
        options
      )

      ctx.status = 200
      ctx.body = {
        success: true,
        ...result
      }
    } catch (error: any) {
      ctx.status = error.message.includes('not found') ? 404 : 500
      ctx.body = {
        success: false,
        error: error.message
      }
    }
  }

  /**
   * 根据ID获取文档
   */
  async getDocumentById(ctx: Context) {
    try {
      const { collectionName, id } = ctx.params;
      
      const result = await dynamicCollectionService.findDocuments(
        collectionName,
        { id: parseInt(id) || id }
      );
      
      const document = result.data[0];
      
      if (!document) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          error: 'Document not found'
        };
        return;
      }
      
      ctx.status = 200;
      ctx.body = {
        success: true,
        data: document
      };
    } catch (error: any) {
      ctx.status = error.message.includes('not found') ? 404 : 500;
      ctx.body = {
        success: false,
        error: error.message
      };
    }
  }

  /**
   * 更新文档
   */
  async updateDocument(ctx: Context) {
    try {
      const { collectionName, id } = ctx.params
      const data = ctx.request.body as any

      // 移除受保护的字段
      delete data._id
      delete data.createdAt
      delete data.updatedAt

      const document = await dynamicCollectionService.updateDocument(
        collectionName,
        id,
        data
      )

      if (!document) {
        ctx.status = 404
        ctx.body = {
          success: false,
          error: 'Document not found'
        }
        return
      }

      ctx.status = 200
      ctx.body = {
        success: true,
        data: document
      }
    } catch (error: any) {
      ctx.status = error.message.includes('not found') ? 404 : 500
      ctx.body = {
        success: false,
        error: error.message
      }
    }
  }

  /**
   * 删除文档
   */
  async deleteDocument(ctx: Context) {
    try {
      const { collectionName, id } = ctx.params
      const result = await dynamicCollectionService.deleteDocument(
        collectionName,
        id
      )
      ctx.status = result.success ? 200 : 404
      ctx.body = result
    } catch (error: any) {
      ctx.status = 500
      ctx.body = {
        success: false,
        error: error.message
      }
    }
  }
}

export const dynamicCollection = new DynamicCollection()
